<?php

namespace app\yy\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\yy\model\Order as OrderModel;
use app\yy\model\OrderGoods as GoodsModel;
use app\yy\model\Domain as DoModel;

class Order extends Admin
{
    public $status = [
        '0' => '失败',
        '1' => '成功',
        '2' => '待付款'
    ];
    public function index()
    {
        $begin_time = $this->request->get('begin_time',date('Y-m-d',strtotime('-6 days')));
        $end_time = $this->request->get('end_time','');
        $where = [];
        if ($begin_time){
            $where[] = ['date_modified', '>=', $begin_time];
        }
        if ($end_time){
            $where[] = ['date_modified', '<', $end_time.' 23:59:59'];
        }

        $succeed = OrderModel::where($where)->where('status',1)->field('count(*) order_succeed_qty,sum(usd_amount) order_succeed_amount')->find();
        $emails = OrderModel::where($where)->where('status',1)->column('email');
        if ($emails){
            $error = OrderModel::where($where)->where('status','<>',1)->where('email','not in', $emails)->field('count(*) order_qty,sum(usd_amount) order_amount')->find();
        }else{
            $error = OrderModel::where($where)->where('status','<>',1)->field('count(*) order_qty,sum(usd_amount) order_amount')->find();

        $orderInfo = array_merge($succeed,$error);

        // 商品列表
        $goods = GoodsModel::where($where)
            ->where('status',1)
            ->group('sku')->field("sum(qty) as qty,sku")->order('qty DESC')->limit(10)->select()->toArray();

        $goods_sku = array_column($goods, 'sku');
        $list = GoodsModel::where('sku', 'in', $goods_sku)->column('*', 'sku');
        $domain_ids = array_unique(array_column($list, 'domain_id'));
        $domain = DoModel::where('id', 'in', $domain_ids)->column('domain', 'id');
        $goods_list = [];
        $k = 1;
        foreach ($goods as $good) {
            $goods_list[$k] = [
                'k' => $k,
                'sku' => $good['sku'],
                'image' => $list[$good['sku']]['image'] ?? '',
                'domain' => $domain[$list[$good['sku']]['domain_id']] ?? '',
                'name' => $list[$good['sku']]['name'] ?? '',
                'qty' => $good['qty']
            ];
            $k++;
        }

        // 站点列表
        $domainOrder = OrderModel::where($where)
            ->where('status',1)
            ->group('domain_id')->field("sum(usd_amount) as amount,domain_id")->order('amount DESC')->limit(10)->select()->toArray();
        $domain_ids = array_unique(array_column($domainOrder, 'domain_id'));
        $domain = DoModel::where('id', 'in', $domain_ids)->column('domain', 'id');

        $order = OrderModel::where($where)->where('status',1)->where('domain_id','in',$domain_ids)->column("count(*) as total,sum(usd_amount) as amount","domain_id");
        $goods = GoodsModel::where($where)->where('status',1)->where('domain_id','in',$domain_ids)->column("sum(qty) as qty","domain_id");
        $domain_list = [];
        $k = 1;
        foreach ($domainOrder as $dOrder) {
            $domain_list[$k] = [
                'k' => $k,
                'domain' => $domain[$dOrder['domain_id']] ?? '',
                'order_total' => $order[$dOrder['domain_id']]['total'] ?? '0',
                'order_amount' => $order[$dOrder['domain_id']]['amount'] ?? '0.00',
                'qty' => $goods[$dOrder['domain_id']] ?? '0'
            ];
            $k++;
        }
        // 域名 成功订单 商品数 销售额
        $this->assign('info', $orderInfo);
        $this->assign('goods_list', $goods_list);
        $this->assign('domain_list', $domain_list);
        return $this->fetch('index');


    }

    public function detail($id = '')
    {
        // 单独网站对比
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day')));
        $list = IpStatModel::where('domain_id', $id)->where('date', '>=', $yesterday)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,date")
            ->group('date')->order('date DESC')->select()->toArray();
        foreach ($list as &$val) {
            $val['date'] = $val['date'] == $yesterday ? '昨日' : '今日';
        }

        // 设备占比
        $date = $this->request->get('date', '1');
        $where = [];
        $time = strtotime(date('Y-m-d', strtotime('-' . $date . ' day')));
        if ($date == 1) {
            $where = [
                ['date', '>=', $time],
                ['date', '<', strtotime(date('Y-m-d'))],
            ];
        } else {
            $where = [
                ['date', '>=', $time]
            ];
        }
//        halt($where);
        $equ_list = IpStatModel::where('domain_id', $id)
            ->where($where)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,is_mobile")
            ->group('is_mobile')
            ->order('is_mobile')
            ->select()->toArray();

        foreach ($equ_list as &$equ) {
            $equ['equ'] = $equ['is_mobile'] ? '移动端' : 'PC端';
        }
        // 地区排行
        $address_list = IpStatModel::where('domain_id', $id)
            ->where($where)
            ->field("sum(ip_num) ip_num_total,sum(pv_num) pv_num_total,country_code,continent_code")
            ->group('country_code,continent_code')
            ->order('country_code,continent_code')
            ->select()->toArray();
        $total = array_sum(array_column($address_list, 'ip_num_total'));
        foreach ($address_list as &$address) {
            $address['scale'] = sprintf("%.2f", ($address['ip_num_total'] / $total) * 100) . '%';
        }

        $this->assign('date', $date);
        $this->assign('list', $list);
        $this->assign('equ_list', $equ_list);
        $this->assign('address_list', $address_list);

        return $this->fetch('detail');


    }


    public function getWhereMap()
    {
        $map = $this->getMap();
        $where = [];
        foreach ($map as $m){
            if ($m[0] == 'domain'){
                $domain_ids = DoModel::where('domain','like', $m[2])->column('id');
                if ($domain_ids){
                    $where[] = ['domain_id','in',$domain_ids];
                }else{
                    $where[] = ['domain_id','<',0];
                }
                continue;
            }
            $where[] = $m;
        }
        return $where;
    }

    public function list()
    {
// 获取查询条件
        $map = $this->getWhereMap();
//        halt($map);
        // 数据列表
        $data_list = OrderModel::where($map)->order('date_modified desc')->paginate();

        // 下单站点
        $domain_ids = array_column($data_list->toArray()['data'],'domain_id');
        $domains = DoModel::where('id','in',$domain_ids)->column('domain','id');
        foreach ($data_list as &$value){
            $value['domain'] = $domains[$value['domain_id']] ?? $value['domain_id'];
        }
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('订单列表') // 设置页面标题
            ->setTableName('order') // 设置数据表名
            ->setSearchArea([
                ['text', 'order_number', '订单号', 'like'],
                ['text', 'domain', '下单站点', 'like'],
                ['text', 'email', '邮箱', 'like'],
                ['text', 'ip', '客户IP', 'like'],
                ['text', 'currency', '货币CODE', 'like'],
                ['select', 'status', '状态', '', '', $this->status],
                ['text', 'billing_country', '国家', 'like'],
                ['daterange', 'date_modified', '交易时间', '', '',['format' => 'YYYY-MM-DD HH:mm']],
            ])
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['order_number', '订单号'],
                ['domain', '下单站点'],
                ['payment', '支付方式'],
                ['status', '状态', 'status', '', $this->status],
                ['email', '邮箱'],
                ['currency', '货币'],
                ['amount', '金额'],
                ['usd_amount', '美元'],
                ['delivery_name', '收件人'],
                ['delivery_country', '收件人国家'],
                ['delivery_phone', '收件人电话'],
                ['date_modified', '交易时间'],
                ['ip', '客户IP'],
//                ['right_button', '操作', 'btn']
            ])
//            ->addTopButtons('add,disable,enable') // 批量添加顶部按钮
//            ->addRightButtons('disable,enable,edit') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                '_checkbox' => 25,
                'id' => 25,
                'order_number' => 85,
                'payment' => 50,
                'status' => 35,
                'email' => 80,
                'currency' => 35,
                'amount' => 35,
                'usd_amount' => 35,
                'delivery_name' => 100,
                'delivery_country' => 80,
                'delivery_phone' => 75,
                'date_modified' => 85,
                'ip' => 80,
//                'right_button' => 30,
            ])
            ->fetch(); // 渲染页面

    }

}